package com.wangwei.spring.rabbit;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 二进制的messageConverter
 * Created by wangwei on 2019/10/13.
 */
public class FileMessageConverter implements MessageConverter {
    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
        System.out.println("-----FileMessageConverter(toMessage)------");
        return null;
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        System.out.println("--------FileMessageConverter(fromMessage)-------");
        Object _ext = message.getMessageProperties().getHeaders().get("ext");
        String ext = (String) _ext;
        String filename = UUID.randomUUID().toString();
        String path = "E:/fileTemp/" + filename + "." + ext;
        File file = new File(path);

        byte[] body = message.getBody();
        try {
            Files.copy(new ByteArrayInputStream(body),file.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;

    }
}
